package utils;

import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

import utils.StringUtils.MyStringBuffer;
import domain.HowToNewInstance;
import domain.MyDate;

public class DateUtils {

	
	//  use date format to do the format job
	private static SimpleDateFormat sdf ;
	
	private static Calendar cal ;
	
	// the pool of MyDate
	private static ObjectPool<MyDate> pool_mydate ;
	
	static{
		cal = Calendar.getInstance();
		sdf = new SimpleDateFormat();
		sdf.setDateFormatSymbols(new DateFormatSymbols(Locale.US));
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
		
		// pool
		pool_mydate = new ObjectPool<MyDate>(new HowToNewInstance<MyDate>() {
			public MyDate newInstance() {
				return new MyDate();
			}
		});
		
	}
	
	public static synchronized String format(String pattern, long time){
		sdf.applyPattern(pattern);
		cal.setTimeInMillis(time);
		return sdf.format(cal.getTime());
	}
	
	
	
	public static String getElapse(long before){
		long current = System.currentTimeMillis();
		long interval = current - before;
		return Elapse.getElapse(interval);
		
	}
	
	public static void main(String[] args) {
		long l = System.currentTimeMillis();
		System.out.println(getDate(l));
	}
	
	private static class Elapse{
		static long s = 1000;
		static long m = 60 * s;
		static long h = 60 * m;
		static long D = 24 * h;
		static long M = 30 * D;
		static long Y = 365 * D;
		
		
		public static String getElapse(long interval){
			MyStringBuffer msb = StringUtils.getNewMyStringBuffer();
			long quotient = 0;
			if((quotient = interval/Y) >0){
				msb.put(quotient);
				msb = quotient>1?msb.put(" years ago"):msb.put(" years ago");
				return msb.getStringAndClose();
			}
			if((quotient = interval/M) >0){
				msb.put(quotient);
				msb = quotient>1?msb.put(" months ago"):msb.put(" month ago");
				return msb.getStringAndClose();
			}
			if((quotient = interval/D) >0){
				msb.put(quotient);
				msb = quotient>1?msb.put(" days ago"):msb.put(" day ago");
				return msb.getStringAndClose();
			}
			if((quotient = interval/h) >0){
				msb.put(quotient);
				msb = quotient>1?msb.put(" hours ago"):msb.put(" hour ago");
				return msb.getStringAndClose();
			}
			if((quotient = interval/m) >0){
				msb.put(quotient);
				msb = quotient>1?msb.put(" minutes ago"):msb.put(" minute ago");
				return msb.getStringAndClose();
			}
			if(interval<0){
				msb.put(interval).put("! In the future? You must be kiding me!");
				return msb.getStringAndClose();
			}
			return "a moment ago";
		}
	}
	
	public static String getDate(long timeMillis){
		MyDate md = pool_mydate.get();
		md.build(timeMillis);
		String date_str = md.toString();
		pool_mydate.returnBack(md);
		return date_str;
	}
	
	
	
}
